const fs = require('fs')
const path = require('path')
const { basename } = require('path')
// canvas库，用于裁剪图片
const { createCanvas, loadImage } = require('canvas')
// 批量获取路径
const glob = require('glob')
// const config = require('./config')

//需要生成的图片尺寸
const configs = [24, 30, 56, 78, 200]

//1024源文件
const imageOrigin = './logo-without-alpha.png'


// 根据宽高获取配置
function getOptions(options, config) {
    const [sourceWidth, sourceHeight] = options
    const { width, height, isWidth, isHeight, scale } = config
    const haveWidth = [width, (sourceHeight * width * scale) / sourceWidth]
    const haveHeight = [(sourceWidth * height * scale) / sourceHeight, height]
    if (width === 0 || height === 0) {
        return [0, 0]
    }
    if (width && height) {
        if (isWidth) {
            return haveWidth
        }
        if (isHeight) {
            return haveHeight
        }
        return [width / scale, height / scale]
    }
    if (width && !height) {
        return haveWidth
    }
    if (height && !width) {
        return haveHeight
    }
    return options.map((item) => item / scale)
}

!(async () => {
    const image = await loadImage(imageOrigin)
    const { width, height } = image

    // 由于使用了扩展运算符展开对象，这里需要为对象定义迭代器
    const obj = { width, height }
    obj[Symbol.iterator] = function () {
        return {
            next: function () {
                let objArr = Reflect.ownKeys(obj)
                if (this.index < objArr.length - 1) {
                    let key = objArr[this.index]
                    this.index++
                    return { value: obj[key] }
                } else {
                    return { done: true }
                }
            },
            index: 0,
        }
    }

    for (let i = 0; i < configs.length; i++) {
        // 默认缩放2倍
        // const options = [width, height].map((item) => item / 2)
        let config = {
            width: configs[i],
            height: '',
            // 根据宽度等比缩放，优先级更高
            isWidth: true,
            // 根据高度等比缩放
            isHeight: false,
            // 宽高整体缩放
            scale: 1,
        }
        const options = getOptions(obj, config)
        const canvas = createCanvas(...options)
        const ctx = canvas.getContext('2d')
        ctx.drawImage(image, 0, 0, ...options)
        fs.writeFile('./images/'+configs[i] + 'x' + configs[i] + '.png', canvas.toBuffer(), (err) => { })
    }
})()
